// @ts-ignore
import { idGeneratorTopic } from '~shared/ipc-topic'
import { browsingHistory } from './browsing-history'
import { asyncTask } from './async-task'
/**
 * @file
 * @description
 * @author 黄敏
 * @since 2025-09-10 17:21
 */
import { contextMenu } from './contextMenu'
import { tab } from './tab'
import { monitor } from './monitor'
import { siteInfo } from './site-info'
import { browser } from './browser'
import 'global-state'

const { ipcRenderer, contextBridge } = require('electron')

const preloads = {
  contextMenu,
  monitor,
  siteInfo,
  tab,
  browsingHistory,
  asyncTask,
  browser,
  ai: {
    ask: (payload: { prompt: string; model?: string; apiKey?: string } | string) => {
      const p = typeof payload === 'string' ? { prompt: payload } : payload
      return ipcRenderer.invoke('ai:ask', p)
    }
  },

  platform: process.platform,
  isMac: process.platform === 'darwin',
  isE2E: process.env?.E2E === 'true',

  generateTabId: (): number => {
    return ipcRenderer.sendSync(idGeneratorTopic.generate, 'tab')
  },
  ipcSend: (topic: string, ...args: any[]) => {
    return ipcRenderer.send(topic, ...args)
  },
  ipcSendSync: (topic: string, ...args: any[]) => {
    return ipcRenderer.sendSync(topic, ...args)
  },
  ipcInvoke: (topic: string, ...args: any[]) => {
    return ipcRenderer.invoke(topic, ...args)
  },
  ipcOn: (topic: string, callback: (...args: any[]) => void) => {
    const cb = (event: unknown, ...args: any[]) => {
      callback(...args)
    }
    ipcRenderer.on(topic, cb)
    return () => {
      ipcRenderer.off(topic, cb)
    }
  }
}
// 将API暴露到全局
contextBridge.exposeInMainWorld('_pre_', preloads)

// TypeScript类型声明
declare global {
  const _pre_: Readonly<typeof preloads>
}
